const AuthService = require('../services/AuthService');

function authenticateToken(req, res, next) {
  // 从请求头获取token
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

  if (!token) {
    return res.status(401).json({
      success: false,
      error: 'Access token required'
    });
  }

  // 验证token
  const result = AuthService.verifyToken(token);
  
  if (!result.success) {
    return res.status(403).json({
      success: false,
      error: 'Invalid or expired token'
    });
  }

  // 将用户信息添加到请求对象
  req.user = {
    id: result.userId,
    username: result.username
  };

  next();
}

module.exports = {
  authenticateToken
};